﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcApplication1.Controllers
{
    public class SignInController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            ViewBag.Message = "Login to your account to begin managing your fleet - intelligently!";
            return View();
        }
        
        [HttpPost]
        public ActionResult Index(SignInModel model)
        {
            if (ModelState.IsValid)
            {
                string password = CheckForUsername(model.Username);
                if (password == null)
                {
                    ViewBag.Message = "The username does not exist in our database, please try again.";
                }
                else if (password == model.Password)
                {
                    string filePath = Server.MapPath(Url.Content("~/Data/sessiondata.txt"));
                    FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.WriteLine(model.Username);
                    }
                    // If the username and password are valid, set a temporary cookie authorizing access.
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    // Redirect to the "Index" View of the "Home" Controller.
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.Message = "The password does not match the username, please try again.";
                }
            }
            return View();
        }

        /// <summary>
        /// Checks to see if a given username is in the database, and returns the password associated with the username if it is present.
        /// </summary>
        /// <param name="username">Username to search for.</param>
        /// <returns>Null if the username is not in the database, password associated with the username otherwise.</returns>
        private string CheckForUsername(string username)
        {
            string line = "";
            string filePath = Server.MapPath(Url.Content("~/Data/signin.txt"));
            using (StreamReader reader = new StreamReader(filePath))
            {
                while (!reader.EndOfStream)
                {
                    line = reader.ReadLine();
                    if (username == line)
                    {
                        line = reader.ReadLine();
                        return line;
                    }
                }
            }
            return null;
        }

    }
}
